import { Model, DataTypes } from 'sequelize';
import sequelize from '../config/database.js';

export default class Friendship extends Model {
  static initModel(sequelize) {
    Friendship.init({
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      userId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      friendId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      status: {
        type: DataTypes.ENUM('pending', 'accepted', 'rejected'),
        defaultValue: 'pending'
      }
    }, {
      sequelize,
      modelName: 'Friendship',
      tableName: 'friendships',
      timestamps: true,
      indexes: [
        {
          unique: true,
          fields: ['userId', 'friendId'],
          name: 'unique_friendship'
        }
      ]
    });

    return Friendship;
  }

  static associate(models) {
    // 定义与发起者的关联
    Friendship.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'user'
    });

    // 定义与接收者的关联
    Friendship.belongsTo(models.User, {
      foreignKey: 'friendId',
      as: 'friend'
    });
  }
}

Friendship.initModel(sequelize);
